package cm.unit4.theme2;

import java.util.ArrayList;
import java.util.Arrays;

public class PrintMatrix {
    public ArrayList<Integer> printMatrix(int[][] matrix) {

        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return null;
        }

        int count = matrix.length * matrix[0].length;
        ArrayList<Integer> list = new ArrayList<>(count);

        int up = 0;
        int down = matrix.length - 1;
        int left = 0;
        int right = matrix[0].length - 1;

        int index = 0;
        int x = 0;
        int y = 0;

        while (index < count) {
            //
            for (y = left; y <= right && index < count; y++) {
                index++;
                list.add(matrix[x][y]);
            }
            y--;
            up++;

            for (x = up; x <= down && index < count; x++) {
                index++;
                list.add(matrix[x][y]);
            }
            x--;
            right--;

            for (y = right; y >= left && index < count; y--) {
                index++;
                list.add(matrix[x][y]);
            }
            y++;
            down--;

            for (x = down; x >= up && index < count; x--) {
                index++;
                list.add(matrix[x][y]);
            }
            x++;
            left++;

        }
        return list;
    }

    public static void main(String[] args) {
        PrintMatrix obj = new PrintMatrix();
        int [][] matrix = {{1,2},{3,4}};
//        int [][] matrix = {{1}};
        System.out.println(obj.printMatrix(matrix));
    }
}
